import Vue from 'vue'
import Router from 'vue-router'
import { routerMap, routes } from './router'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'
Vue.use(Router)

const router = new Router({
  mode: 'history', // 后端支持可开
  // routes: routerMap
  routes // es6键值相同简写
})

router.beforeEach((to, from, next) => {
// if (to.name === 'login') next()
// else next({ name: 'login' })
  const token = getToken()
  if (token) {
    // console.log(store.state.router.hasGetRules)
    if (!store.state.router.hasGetRules) {
      store.dispatch('GetUserInfo').then(rules => {
        store.dispatch('concatRoutes', rules).then(routers => {
          console.log('生成可访问路由：', routers)
          router.addRoutes(routers)
          next({ ...to, replace: true })
        }).catch(() => {
          next({ name: 'login' })
        })
      }).catch(() => {
        setToken('')
        next({ name: 'login' })
      })
    } else {
      if (to.name === 'login') next({ path: '/' })
      else next()
    }
  } else {
    if (to.name === 'login') next()
    else next({ name: 'login' })
  }
})

export default router
